package com.wmz.controller;

import com.github.pagehelper.PageInfo;
import com.wmz.entity.User;
import com.wmz.query.UserQuery;
import com.wmz.result.R;
import com.wmz.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author wmz
 * @date 2024/2/18 14:34
 * @description UserController
 */
@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private UserService userService;
    /**
     * 获取登录用户的信息
     * @param authentication
     * @return
     */
    @GetMapping("/login/info")
    public R loginInfo(Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        return R.OK(user);
    }

    /**
     * 判断是否需要免登录
     * @return
     */
    @GetMapping("/login/free")
    public R loginFree(){
        return R.OK();
    }

    /**
     * 分页查询用户列表
     * @param pageNum
     * @return
     */
    @GetMapping("/users")
    public R userPage(@RequestParam(value = "pageNum",required = false) Integer pageNum){
        if(pageNum == null) {
            pageNum = 1;
        }
        PageInfo<User> pageInfo = userService.getUserByPage(pageNum);
        return R.OK(pageInfo);
    }
    @GetMapping("/user/{id}")
    public R userDetail(@PathVariable("id") Integer id) {
        User user = userService.getUserById(id);
        return R.OK(user);
    }

    /**
     * 新增用户
     * @param userQuery
     * @param token
     * @return
     */
    @PostMapping("/user")
    public R addUser(UserQuery userQuery,@RequestHeader("Authorization") String token) {
        userQuery.setToken(token);
        int count = userService.insertUser(userQuery);
        return count>0?R.OK():R.FAIL();
    }

    /**
     * 修改用户
     * @param userQuery
     * @param token
     * @return
     */
    @PutMapping("/user")
    public R editUser(UserQuery userQuery,@RequestHeader("Authorization") String token) {
        userQuery.setToken(token);
        int count = userService.updateUser(userQuery);
        return count>0?R.OK():R.FAIL();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/user/{id}")
    public R delUser(@PathVariable("id") Integer id) {
        int count = userService.delUser(id);
        return count>0?R.OK():R.FAIL();
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @DeleteMapping("/user")
    public R batchDelUser(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int count = userService.batchDelUser(idList);
        return count >= idList.size() ? R.OK() : R.FAIL();
    }
}
